import os
import pandas as pd
from py2neo import Graph, Node

"""
neo4j 删除节点及其关系：
MATCH (n:BC_Person)-[r]-() DELETE n,r

neo4j 删除节点：
MATCH (n:BC_Person) DELETE n


match( n: UNIT {name:'进样线'} )-[rel:method]->(p) return p.name
"""

g = Graph(
    host="127.0.0.1",  # neo4j 搭载服务器的ip地址，ifconfig可获取到
    http_port=7474,  # neo4j 服务器监听的端口号
    user="neo4j",  # 数据库user name，如果没有更改过，应该是neo4j
    password="root")


def create_node(label, node_name):
    node = Node(label, name=node_name)
    g.create(node)


def create_diseases_nodes(label, info):
    """
    创建中心节点
    :param self: 
    :param disease_infos: 
    :return: 
    """

    node = Node(label, name=info)
    g.create(node)


def create_relationship(start_node, end_node, edges, rel_type, rel_name):
    """
    创建实体关系
    :param self: 
    :param start_node: 
    :param end_node: 
    :param edges: 
    :param rel_type: 
    :param rel_name: 
    :return: 
    """
    count = 0
    # 去重处理
    set_edges = []
    for edge in edges:
        set_edges.append('###'.join(edge))
    all = len(set(set_edges))
    for edge in set(set_edges):
        edge = edge.split('###')
        p = edge[0]
        q = edge[1]
        query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
            start_node, end_node, p, q, rel_type, rel_name)
        try:
            g.run(query)
            count += 1
            print(rel_type, count, all)
        except Exception as e:
            print(e)


base_path = os.path.dirname(os.path.dirname(__file__))

entry_have = pd.read_csv(os.path.join(base_path, 'data/entries_relation_have.csv'))
entry_belong = pd.read_csv(os.path.join(base_path, 'entries_relation_belong.csv'))
entry_apparance = pd.read_csv(os.path.join(base_path, 'entries_relation_attribute.csv'))
entry_method = pd.read_csv(os.path.join(base_path, 'entries_relation_method.csv'))

"""
读取关系
"""
rels_have, rels_apparance, rels_belong, rels_method = [], [], [], []

for row in range(len(entry_have)):
    rels_have.append(entry_have.loc[row, ['entry1', 'entry2']].values.tolist())

for row in range(len(entry_belong)):
    rels_belong.append(entry_belong.loc[row, ['entry1', 'entry2']].values.tolist())

for row in range(len(entry_apparance)):
    rels_apparance.append(entry_apparance.loc[row, ['entry2', 'entry1']].values.tolist())

for row in range(len(entry_method)):
    rels_method.append(entry_method.loc[row, ['entry1', 'entry2']].values.tolist())

"""
创建节点
# """
for instrument_type in entry_have['entry1'].unique():
    create_diseases_nodes(label='INSTRUMENT', info=instrument_type)

for unit in entry_have['entry2'].unique():
    create_node(label='UNIT', node_name=unit)

for sub_unit in entry_belong['entry1'].unique():
    create_node(label='SUB_UNIT', node_name=sub_unit)

for apparance in entry_apparance['entry1'].unique():
    create_node(label='APPARANCE', node_name=apparance)

for method in entry_method['entry2'].unique():
    create_node(label='METHOD', node_name=method)

"""
创建节点关系
"""
create_relationship('INSTRUMENT', 'UNIT', rels_have, 'have', '拥有部位')
create_relationship('SUB_UNIT', 'UNIT', rels_belong, 'belong', '属于')
create_relationship('UNIT', 'APPARANCE', rels_apparance, 'apparance', '异常表现')
create_relationship('UNIT', 'METHOD', rels_method, 'method', '处理方法')
